
import 'dart:convert';
import 'dart:io';
import 'package:flutter_app/class/MyApp9.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/class/Model/MyApp10Model.dart';
import 'package:http/http.dart' as http;

class MyApp10 extends StatelessWidget {
  const MyApp10({super.key});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: "网络异步请求",
      theme: ThemeData(
        primarySwatch: Colors.deepPurple
      ),
      home: const MyRequestTest(),
    );
  }
}

class MyRequestTest extends StatefulWidget {
  const MyRequestTest({super.key});
  
  @override
  State<MyRequestTest> createState() => _MyRequestState();
}

class _MyRequestState extends State<MyRequestTest> {

  var strMsg = "请点击按钮测试";
  var arrData = <MyApp10Model>[];
  bool isLoad = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    debugPrint("这是初始化方法");
  }

  //MARK: - _isLoad
  void _isLoad(){
    if(!isLoad) {
      //loadData();
      httpRequest();
    }
    else{
      debugPrint('已请求完成');
    }
  }

  setText(){
    if(!isLoad){
       return Text(strMsg);
    }
    else{
      if(arrData.isNotEmpty) {
        return ListView.builder(
            padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
            itemCount: arrData.length,
            itemBuilder: (context,i){
              if(arrData.length <= i) {
                return null;
              }

              if(i < arrData.length - 1) {
                return Column(
                  children: [
                    cellBindDataFor(arrData[i],i),
                    const Divider(),
                  ],
                );
              }
              else {
                return cellBindDataFor(arrData[i],i);
              }
            },
        );
      }
      else{
        return const CircularProgressIndicator();
      }
    }
  }

  Widget cellBindDataFor(MyApp10Model model, final index) {
    var sno = _hexToInt('e3d${model.userId}') ;

    return ListTile(
      leading: const CircleAvatar(
        radius: 25,
        backgroundImage: NetworkImage('https://gips1.baidu.com/it/u=1971954603,2916157720&fm=3028&app=3028&f=JPEG&fmt=auto?w=1920&h=2560'),
      ),
      title: Text(
        model.title,
        style: const TextStyle(fontWeight: FontWeight.bold,fontSize: 18),
      ),
      subtitle: Text(
        '$index、${model.body}',
        style: const TextStyle(fontSize: 14),
      ),
      trailing: Icon(
          IconData(sno, fontFamily: 'MaterialIcons'),
          color: null,
      ),
      onTap: (){
        debugPrint("我是点击：${model.id}");
      },
      onLongPress: (){
        debugPrint("我是长按：${model.id}");
      },
      isThreeLine: false,
    );
  }

  /* 异步网络请求(原生的) */
  void loadData() async {
    try {
      final httpClient = HttpClient();
      final url = Uri.http('https://jsonplaceholder.typicode.com', '/posts');

      final request = await httpClient.getUrl(url);
      final response = await request.close();
      if(response.statusCode == HttpStatus.ok){
        debugPrint("请求成功");

        final responseBody = await response.transform(utf8.decoder).join();
        final data = jsonDecode(responseBody);

        for(int i = 0,len = data.length; i < len; i++) {
           arrData.add(MyApp10Model.fromJson(data[i]));
        }

        //更新 UI
        setState(() {
          debugPrint("UI绘制成功");
          isLoad = true;
        });
      }
      else{
         debugPrint('请求失败，详见：${response.reasonPhrase}');

         setState(() {
           isLoad = false;
         });
      }
    } catch (e, s) {
      debugPrint("请求异常，详见:$s");

      setState(() {
        isLoad = false;
      });
    }
  }

  /* http 网络请求库 */
  void httpRequest() async {
    setState(() {
      isLoad = true;
    });

     const String strUrl = "https://jsonplaceholder.typicode.com/posts";
     try {
       http.Response response = await http.get(Uri.parse(strUrl));

       if(response.statusCode == HttpStatus.ok){
         arrData.clear();
         for(var m in jsonDecode(response.body)){
           arrData.add(MyApp10Model.fromJson(m));
         }

         setState(() {
           isLoad = true;
         });
       }
       else{
         setState(() {
           isLoad = false;
         });
       }
     }
     catch (e, s) {
       strMsg = s.toString();
       debugPrint("请求异常，详见:$s");

       setState(() {
         isLoad = false;
       });
     }
  }

  /* 颜色转换 */
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw const FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
         appBar: AppBar(
           title: const Text('网络异步请求'),
           actions: [
             IconButton(icon: const Icon(Icons.arrow_right),
                 onPressed: (){
                    Navigator.push(context, MaterialPageRoute(builder: (context) => const MyApp9()));
                 })
           ],
         ),
         body: Center(
             child: setText(),
         ),
         floatingActionButton: FloatingActionButton(
           onPressed: _isLoad,
           tooltip: '点击开始异步加载测试',
           child: const Icon(Icons.file_download),
         ),
    );
  }
}

